package com.smart.nine.spel.expr.collection;

import com.smart.nine.spel.expr.User;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数组，集合类型解析
 *
 * @author junrui.wang
 * @create 2019/3/21
 */
public class CollectionExprSample {
    public static void main(String[] args) {
        User user = new User();
        List<String> interestsArray = new ArrayList();
        interestsArray.add("c");
        interestsArray.add("b");
        Map<String, String> interestsMap = new HashMap();
        interestsMap.put("interests1", "v");
        user.setInterestsArray(interestsArray);
        user.setInterestsMap(interestsMap);


        ExpressionParser parser = new SpelExpressionParser();

        EvaluationContext context = new StandardEvaluationContext();
        EvaluationContext contextUser = new StandardEvaluationContext(user);

        //getValue() = getValue(new StandardEvaluationContext());

        //数组表达式解析
        int[] array1 = (int[]) parser.parseExpression("new int[]{1,2,3}").getValue();
        System.out.println(array1.toString());

        int[][] array2 = (int[][]) parser.parseExpression("new int[2][3]").getValue();
        System.out.println(array2.toString());

        //不支持多维数组初始化
        /*
            int[][] array3 = (int[][]) parser.parseExpression("int[2][3]{{1,2,3},{4,5,6}}").getValue(context);
            System.out.println(array3);
         */

        //list表达式解析
        List list = (List) parser.parseExpression("{1,2,3,4}").getValue();
        System.out.println(list.toString());
        List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getValue();
        System.out.println(listOfLists);

        //列表字符串解析
        Map user1 = (Map) parser.parseExpression("{name:'Tom',credits:100}").getValue();
        System.out.println(user1.toString());
        List user2 = (List) parser.parseExpression("{{name:'Tom',credits:100},{name:'John',credits:100}}").getValue();
        System.out.println(user2.toString());

        //从列表数组里取值,interestsArray,interestsMap是User根对象的属性，
        //EvaluationContext contextUser = new StandardEvaluationContext(根对象);
        String value = (String) parser.parseExpression("interestsArray.get(0)").getValue(contextUser);
        System.out.println(value);
        String value2 = (String) parser.parseExpression("interestsArray.get(1)").getValue(contextUser);
        System.out.println(value2);
        String value3 = (String) parser.parseExpression("interestsMap['interests1']").getValue(contextUser);
        System.out.println(value3);

    }
}
